package com.ruoyi.jihuo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.jihuo.constant.TaoApiConstant;
import com.ruoyi.jihuo.service.CallbackService;
import com.ruoyi.jihuo.service.IJhTmAccountService;
import com.ruoyi.jihuo.service.IJhTmTemplateService;
import com.ruoyi.system.service.ISysConfigService;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.TopAuthTokenCreateRequest;
import com.taobao.api.response.TopAuthTokenCreateResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

/**
 * @Author：LXY
 * @DATE：2025-09-15 16:10
 * @Description：
 */
@Slf4j
@Service
public class CallbackServiceImpl implements CallbackService {
    @Autowired
    private IJhTmAccountService jhTmAccountService;
    @Autowired
    private ISysConfigService iSysConfigService;
    @Autowired
    private IJhTmTemplateService jhTmTemplateService;
    @Autowired
    private RedisCache redisCache;
    @Override
    public void processingAuthCallback(String authCode, String feature) {
        //获取SessionKey
        String url = TaoApiConstant.TAOBAO_LOGISTICS_HTTPS_API_URL;
        //根据feature从redis中获取AppKey和Secret
        String redisKey = feature;
        String configJson = redisCache.getCacheObject(redisKey);
        JSONObject config = JSONObject.parseObject(configJson);
        String appkey = config.getString("appKey");
        String secret = config.getString("appSecret");
        TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
        TopAuthTokenCreateRequest req = new TopAuthTokenCreateRequest();
        req.setCode(authCode);
        try {
            TopAuthTokenCreateResponse rsp = client.execute(req);
            String jsonBody = rsp.getBody();

            ObjectMapper mapper = new ObjectMapper();
            JsonNode rootNode = mapper.readTree(jsonBody);
            if (rootNode.path("top_auth_token_create_response").isMissingNode()){
                log.error("淘宝授权回调异常-淘宝响应结果::{}", jsonBody);
                throw new RuntimeException(jsonBody);
            }
            // 获取嵌套的token_result字符串
            String tokenResultStr = rootNode.path("top_auth_token_create_response")
                    .path("token_result").asText();

            // 再次解析token_result中的JSON
            JsonNode tokenNode = mapper.readTree(tokenResultStr);
            String accessToken = tokenNode.path("access_token").asText();
            String taobaoUserNick = tokenNode.path("taobao_user_nick").asText();
            String decodedNick = URLDecoder.decode(taobaoUserNick, StandardCharsets.UTF_8.name());
            if (StringUtils.isBlank(accessToken) && StringUtils.isBlank(decodedNick)){
                throw new RuntimeException("未从"+tokenNode+"中解析出accessToken或taobaoUserNick");
            }
            log.info("淘宝授权回调成功-昵称/账号:{},sessionKey:{}", decodedNick,accessToken);
            // 保存SessionKey
            Long accountId = jhTmAccountService.updateSessionKeyByName(decodedNick, accessToken);
            //获取运费模板
            try {
                String shopFreightTemplate = jhTmTemplateService.getShopFreightTemplate(accessToken, appkey, secret);
                redisCache.setCacheMapValue((CacheConstants.SHOP_FREIGHT_TEMPLATE), accountId.toString(), shopFreightTemplate);
            }catch (Exception e){
                log.error("获取店铺运费模板异常:{}", e.getMessage());
            }
        }catch (Exception e) {
            log.error("淘宝授权回调异常:{}", e.getMessage());
            throw new RuntimeException("淘宝授权回调异常:"+e);
        }
    }
}
